package com.example.client;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.server.IUserService;

public class MainActivity extends AppCompatActivity {
    private IUserService mService;
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            Log.d("-----------------", "connect success");
            mService = IUserService.Stub.asInterface(iBinder);//bridge为IMyAidlInterface
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.d("-----------------", "error disconnect");
            mService = null;
        }
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bind_service:
                Intent intent = new Intent();
                intent.setPackage("com.example.server");
                intent.setAction("com.example.server.action");
                boolean a = bindService(intent, conn, Context.BIND_AUTO_CREATE);
                Toast.makeText(this, "服务绑定" + a, Toast.LENGTH_LONG).show();
                break;
            case R.id.get_user_name:
                try {
                    String name = mService.getUserName();
                    Toast.makeText(this, "从server获取的name是:" + name, Toast.LENGTH_LONG).show();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }
    }
}
